package edu.bbu.bibliospring.backend.model;

import java.io.Serializable;
import java.util.UUID;
import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;

@MappedSuperclass
public abstract class AbstractModel implements Serializable {
	private static final long serialVersionUID = 1L;
    @Column (name = "uuid", nullable = false, length = 36, unique = true)
    protected String uuid;
	
	@Override
	public int hashCode() {
		return getUuid().hashCode();
	}
	
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof AbstractModel))
			return false;
		return getUuid().equals(((AbstractModel) obj).getUuid());
	}
	
	//@Column (name = "uuid", nullable = false, length = 36, unique = true)
	public String getUuid() {
		ensureUuid();
		return uuid;
	}
	
	private void setUuid(final String uuid){
		this.uuid = uuid;
	}
	
	@PrePersist
	public void onPrePersist() {
		ensureUuid();
	}
	
	private void ensureUuid() {
		if (uuid == null)
			setUuid(UUID.randomUUID().toString());
	}
}
